// XMPP服务器BOSH地址
var BOSH_SERVICE = '/http-bind/'

// XMPP连接
var connection = null

// 当前状态是否连接
var connected = false

// 当前登录的JID
var from_jid = ''

function get_jid(type) {
    var jid = $('#input-' + type + '-jid').val()
    return jid.indexOf('@') > 0 ? jid : jid + '@localhost'
}
// 连接状态改变的事件
function onConnect(status) {
    if (status == Strophe.Status.CONNFAIL) {
        $("#msg").prepend("CONNFAIL <br>")
    } else if (status == Strophe.Status.AUTHFAIL) {
        $("#msg").prepend("login fail <br>")
    } else if (status == Strophe.Status.DISCONNECTED) {
        $("#msg").prepend("DISCONNECTED <br>")
        connected = false
    } else if (status == Strophe.Status.CONNECTED) {
        $("#msg").prepend("CONNECTED <br>")
        connected = true

        // 当接收到<message>节，调用onMessage回调函数
        connection.addHandler(onMessage, null, 'message', null, null, null)

        // 首先要发送一个<presence>给服务器（initial presence）
        connection.send($pres().tree())

        // 发送<presence>元素，加入房间
        var pres = $pres({
            from: get_jid('from'),
            to: get_jid('to')
        }).c('x',{xmlns: 'http://jabber.org/protocol/muc'}).tree()
        connection.send(pres)
        //connection.sendIQ(pres)//获取房间列表
    }
}

// 接收到<message>
function onMessage(msg) {

    console.log('onMessage: ', msg)
    // 解析出<message>的from、type属性，以及body子元素
    var from = msg.getAttribute('from')
    var type = msg.getAttribute('type')
    var elems = msg.getElementsByTagName('body')

    if (type == 'chat' && elems.length > 0) {
        var body = elems[0]
        $(body).addClass('left')
        $("#msg").prepend(body)
        var title = '<p class="left">' + from.substring(0, from.indexOf('/')) + ':</p>'
        $("#msg").prepend(title)
    } else if (type == 'groupchat' && elems.length > 0) {

    }
    return true
}

$(document).ready(function() {

    // 通过BOSH连接XMPP服务器
    $('#btn-login').click(function() {
        if(!connected) {
            connection = new Strophe.Connection(BOSH_SERVICE)
            connection.connect(get_jid('from'), $("#input-pwd").val(), onConnect)
        }
    })

    // 发送消息
    $("#btn-send").click(function() {
        if(connected) {
            var body = $("#input-msg").val()
            var to_jid = get_jid('to')
            if (!body) {
                return
            }
            if (!to_jid) {
                return
            }
            // 创建一个<message>元素并发送
            var msg = $msg({
                to: to_jid,
                from: get_jid('from'),
                // type: 'groupchat'
                type: 'chat'
            }).c("body", null, body)
            connection.send(msg.tree())

            var html = "<p class='right'> me:<br/>"
            html += body+ '</p>'
            $("#msg").prepend(html)
            $("#input-msg").val('')
        } else {
            $("#msg").prepend("not login <br>")
        }
    })
})
